package com.tuzhi.security.service.impl;


import com.tuzhi.common.constants.security.CacheConstants;
import com.tuzhi.common.domain.LoginUserBO;
import com.tuzhi.security.service.TokenStoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TokenStoreServiceImpl implements TokenStoreService {

    /**
     * 这里存储的key是CacheConstants.LOGIN_TOKEN_KEY + uuid（token的login_user_key）
     */
    static Map<String, LoginUserBO> map = new HashMap<>();

    @Override
    public LoginUserBO getLoginUser(String userId) {
        return map.get(userId);
    }

    @Override
    public synchronized void delLoginUser(String userId) {
        map.remove(userId);
    }

    @Override
    public synchronized void storeLoginUser(LoginUserBO loginUserBO) {
        map.put(loginUserBO.getUserName(), loginUserBO);
    }

    @Override
    public <T> void setCacheObject(String key, T value, Integer timeout, TimeUnit timeUnit) {

    }

    @Override
    public String getTokenKey(String uuid) {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }

    @Override
    public void userTokenCheck() {
        Iterator<Map.Entry<String, LoginUserBO>> iterator = map.entrySet().iterator();
        Map.Entry<String, LoginUserBO> entry;
        while (iterator.hasNext()) {
            entry = iterator.next();
            LoginUserBO loginUserBO = entry.getValue();
            Date exp = new Date(loginUserBO.getExpireTime());
            if (exp.before(new Date())) {
                log.info("userId={},nickName={},已过期，从用户token缓存中移除。", loginUserBO.getUserName(), loginUserBO.getNickName());
                iterator.remove();
            }
        }
    }
}

